from rest_framework import serializers
from .models import *
import re
from rest_framework.exceptions import ValidationError
import datetime


class CodeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Code
        fields = ["phone"]

    def validate_phone(self, phone):
        if not re.match("^1[3578]\d{9}$", phone):
            raise ValidationError("手机号格式错误")

        return phone


class UserSerialzier(serializers.ModelSerializer):
    code = serializers.CharField(max_length=6, write_only=True)

    class Meta:
        model = User
        fields = ["username", "password", "phone", "type", "code"]

    def validate(self, attrs):
        code = attrs["code"]
        phone = attrs["phone"]

        cobj = Code.objects.filter(phone=phone).order_by("-created").first()

        if not cobj:
            raise ValidationError("没有给该手机号发送过短信")

        if code != cobj.code:
            raise ValidationError("验证码输入错误")

        # if datetime.datetime.now() > cobj.created + datetime.timedelta(minutes=2):
        #     raise ValidationError("验证码超过一分钟失效")

        del attrs["code"]
        return attrs

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = "__all__"


class HeroSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hero
        fields = "__all__"
